/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import classe.controlador.SetorJpaController;
import classe.controlador.UsuarioJpaController;
import classe.controlador.exceptions.IllegalOrphanException;
import classe.controlador.exceptions.NonexistentEntityException;
import classe.entidade.Setor;
import classe.entidade.Usuario;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.PersistenceException;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Pinheiro
 */
public class ConsultarUsuarios extends javax.swing.JFrame {

    /**
     * Creates new form ConsultarUsuarios
     */
    public ConsultarUsuarios() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        excluirUsuario = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaUsuario = new javax.swing.JTable();
        editarUsuario = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Usuários"));

        excluirUsuario.setText("Excluir");
        excluirUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                excluirUsuarioActionPerformed(evt);
            }
        });

        tabelaUsuario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Nome", "CPF", "Login", "Senha"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabelaUsuario.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                tabelaUsuarioPropertyChange(evt);
            }
        });
        jScrollPane1.setViewportView(tabelaUsuario);
        tabelaUsuario.getColumnModel().getColumn(0).setMinWidth(30);
        tabelaUsuario.getColumnModel().getColumn(0).setPreferredWidth(30);
        tabelaUsuario.getColumnModel().getColumn(0).setMaxWidth(30);

        editarUsuario.setText("Editar");
        editarUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editarUsuarioActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 648, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(editarUsuario)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(excluirUsuario)
                        .addGap(5, 5, 5)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(editarUsuario)
                    .addComponent(excluirUsuario))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 700, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 345, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void excluirUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_excluirUsuarioActionPerformed
        excluiUsuario();
    }//GEN-LAST:event_excluirUsuarioActionPerformed

    private void editarUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editarUsuarioActionPerformed
        editaUsuario();
    }//GEN-LAST:event_editarUsuarioActionPerformed

    private void tabelaUsuarioPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_tabelaUsuarioPropertyChange
        // TODO add your handling code here:
    }//GEN-LAST:event_tabelaUsuarioPropertyChange

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        preencherTabela();
    }//GEN-LAST:event_formWindowActivated
    
    
    private void preencherTabela() {
        limparTabela();

        UsuarioJpaController daoUsuario = new UsuarioJpaController();
        ArrayList<Usuario> arrayUsuario = new ArrayList<Usuario>();

        try {

            // Captura todas os materiais
                arrayUsuario.addAll(daoUsuario.findUsuarioEntities());
           
            
        } catch (PersistenceException e) {
            JOptionPane.showMessageDialog(rootPane, "Ocorreu um erro durante a conexão com o banco de dados.");
        }

        Iterator iterator = arrayUsuario.iterator();
        // Percorre todo o array dos usuarios
        while (iterator.hasNext()) {
            Usuario usuario = (Usuario) iterator.next();
            Object[] linha;
            System.out.println(usuario.getNome());
            // Adiciona os valores dos campos a variável do tipo objeto "linha"
            // que será usada para preencher a tabela com as três colunas
            linha = new Object[]{
                usuario.getId(),
                usuario.getNome(),
                usuario.getCpf().toUpperCase(),
                usuario.getLogin(),
                usuario.getSenha()
            };
                

            // Pega o modelo da tabela, e em seguida adiciona uma linha com os dados atribuidos a 
            // do tipo objeto acima
            DefaultTableModel catalogoModel = (DefaultTableModel) tabelaUsuario.getModel();
            catalogoModel.addRow(linha);

        }

    }
    
    private void limparTabela() {
        DefaultTableModel usuarioModel = (DefaultTableModel) tabelaUsuario.getModel();

        // Captura o número de linhas da tabela 
        int numeroLinhas = usuarioModel.getRowCount();

        // Remove as linhas da tabela
        for (int i = 0; i < numeroLinhas; i++) {
            usuarioModel.removeRow(0);
        }
    }
    
    private void excluiUsuario() {
        int linha = tabelaUsuario.getSelectedRow();
         int idUsuario = (int) tabelaUsuario.getValueAt(linha, 0);
         String nomeUsuario = (String) tabelaUsuario.getValueAt(linha, 1);
         String cpfUsuario = (String) tabelaUsuario.getValueAt(linha, 2);
         String loginUsuario = (String) tabelaUsuario.getValueAt(linha, 3);
         String senhaUsuario = (String) tabelaUsuario.getValueAt(linha, 4);
         
         UsuarioJpaController daoUsuario = new UsuarioJpaController();
        try {
            daoUsuario.destroy(idUsuario);
            preencherTabela();
        } catch (IllegalOrphanException ex) {
            Logger.getLogger(SetorRequisitante.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(SetorRequisitante.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
     private void editaUsuario() {
         int linha = tabelaUsuario.getSelectedRow();
         int idUsuario = (int) tabelaUsuario.getValueAt(linha, 0);
         String nomeUsuario = (String) tabelaUsuario.getValueAt(linha, 1);
         String cpfUsuario = (String) tabelaUsuario.getValueAt(linha, 2);
         String loginUsuario = (String) tabelaUsuario.getValueAt(linha, 3);
         String senhaUsuario = (String) tabelaUsuario.getValueAt(linha, 4);
         
         UsuarioJpaController daoUsuario = new UsuarioJpaController();
         
         CadastroUsuario janelaCadastro = new CadastroUsuario(idUsuario, nomeUsuario, cpfUsuario, loginUsuario, senhaUsuario);
         janelaCadastro.setVisible(true);
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ConsultarUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ConsultarUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ConsultarUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ConsultarUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ConsultarUsuarios().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton editarUsuario;
    private javax.swing.JButton excluirUsuario;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabelaUsuario;
    // End of variables declaration//GEN-END:variables

    

   
}
